// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/_components/image-form.tsx
'use client';
import React, {useState} from 'react';
import * as z from "zod";
import {useRouter} from "next/navigation";
import toast from "react-hot-toast";
import {Button} from "@/components/ui/button";
import {ImageIcon, Pencil, PlusCircle} from "lucide-react";
import {Course} from '@prisma/client'
import FileUpload from "@/components/learn/file-upload";
import Image from "next/image";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";

interface Props {
    initialData: Course
    courseId: string
}

const formSchema = z.object({
    imageUrl: z.string().min(1, {
        message: 'Image is required',
    })
})

const ImageForm = ({initialData, courseId}: Props) => {
    const router = useRouter()

    const [isEditing, setIsEditing] = useState(false)
    const toggleEdit = () => setIsEditing((current) => !current)

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const res = await fetch(`/api/course/${courseId}`, {
                method: "PATCH",
                body: JSON.stringify(values),
                headers: {
                    "Content-Type": "application/json"
                }
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success(`更新成功`)
            toggleEdit()
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    const {mutate: uploadImg, isPending} = useGenerateUploadUrl();

    return (
        <div className={`mt-6 border bg-slate-100 rounded-md p-4`}>
            <div className={`font-medium flex items-center justify-between`}>
                Course image
                <Button variant={'ghost'}
                        onClick={toggleEdit}>
                    {isEditing && (
                        <>Cancel</>
                    )}
                    {!isEditing && !initialData.imageUrl && (
                        <>
                            <PlusCircle className={`size-4 mr-2`}/>
                            Add an image
                        </>
                    )}
                    {!isEditing && initialData.imageUrl && (
                        <>
                            <Pencil className={`size-4 mr-2`}/>
                            Edit image
                        </>
                    )}
                </Button>
            </div>
            {!isEditing && (
                !initialData.imageUrl ? (
                    <div className={`flex items-center justify-center h-60 bg-slate-200 rounded-md`}>
                        <ImageIcon className={`size-10 text-slate-500`}/>
                    </div>
                ) : (
                    <div className={`relative aspect-video mt-2`}>
                        <Image
                            alt={'Upload'}
                            fill
                            className={`object-cover rounded-md`}
                            src={initialData.imageUrl}
                        />
                    </div>
                )
            )}
            {isEditing && (
                <div>
                    <FileUpload
                        accept={'image/*'}
                        // endpoint={'courseImage'}
                        onChange={async (f) => {
                            if (f) {
                                let url = await uploadImg({
                                    // @ts-ignore
                                    image: f,
                                    prefix: `course/${courseId}/covers`
                                })
                                if (!url || isPending) return
                                await onSubmit({imageUrl: url})
                            }
                        }}
                    />
                    <div className={`text-xs text-muted-foreground mt-4`}>
                        16:9 aspect ratio recommended
                    </div>
                </div>
            )}
        </div>
    );
};

export default ImageForm;